package com.hitqz.robot.daemon.quartz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hitqz.robot.api.business.entity.GoodsBuffersEntity;
import com.hitqz.robot.api.business.entity.GoodsGroupEntity;
import com.hitqz.robot.biz.service.GoodsBuffersService;
import com.hitqz.robot.biz.service.GoodsGroupService;
import com.hitqz.robot.daemon.quartz.model.AgvCallDataDto;
import com.hitqz.robot.daemon.quartz.service.AgvStoreService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class NewAgvStoreServiceImpl implements AgvStoreService {

    private final GoodsBuffersService goodsBuffersService;

    private final GoodsGroupService goodsGroupService;

    @Override
    public List<GoodsBuffersEntity> findBestPlace(String src, String des, Integer num, String zx, Integer srcPlace, List<AgvCallDataDto> storeData) {
        String realStoreName;
        switch (srcPlace) {//1-旧轴 2-返修 3-报废
            case 1:
                realStoreName = "旧轴";
                break;
            case 2:
                realStoreName = "返修";
                break;
            case 3:
                realStoreName = "报废";
                break;
            default:
                log.error("不存在的轴型：{}", srcPlace);
                return Collections.emptyList();
        }
        if ("911017".equals(src)) {
            return this.findBestPlaceForTake(num, realStoreName);
        } else if ("911017".equals(des)) {
            return this.findBestPlaceForPut(num, zx, storeData, realStoreName);
        }
        return Collections.emptyList();
    }

    private List<GoodsBuffersEntity> findBestPlaceForPut(Integer num, String zx, List<AgvCallDataDto> storeData,
                                                         String realStoreName) {
        List<GoodsBuffersEntity> bestPlaceList = new ArrayList<>();
        List<GoodsGroupEntity> allGoodsGroup = goodsGroupService.list();
        List<GoodsBuffersEntity> allGoodsBuffers = goodsBuffersService.list();
        if ("报废".equals(realStoreName)) {// 从第1组-->第8组，有空位就存
            for (GoodsGroupEntity group : allGoodsGroup) {
                bestPlaceList = this.searchBestPlaceListForPut(allGoodsBuffers, group.getId(), num);
                if (!bestPlaceList.isEmpty()) break;
            }
        } else if ("旧轴".equals(realStoreName)) { //从第2组-->第8组，有空位就存；2-8组都没有空位则在第1组找空位存
            for (GoodsGroupEntity group : allGoodsGroup) {
                if (group.getId() == 1) continue;
                bestPlaceList = this.searchBestPlaceListForPut(allGoodsBuffers, group.getId(), num);
                if (!bestPlaceList.isEmpty()) break;
            }
            if (bestPlaceList.isEmpty()) {
                bestPlaceList = this.searchBestPlaceListForPut(allGoodsBuffers, 1, num);
            }
        } else if ("返修".equals(realStoreName)) { //从第8组-->第1组，有空位就存；
            allGoodsGroup = allGoodsGroup.stream().sorted(Comparator.comparingInt(GoodsGroupEntity::getId).reversed()).toList();
            for (GoodsGroupEntity group : allGoodsGroup) {
                bestPlaceList = this.searchBestPlaceListForPut(allGoodsBuffers, group.getId(), num);
                if (!bestPlaceList.isEmpty()) break;
            }
        }
        if (!bestPlaceList.isEmpty()) {
            for (int i = 0; i < bestPlaceList.size(); i++) {
                GoodsBuffersEntity goodsBuffersEntity = bestPlaceList.get(i);
                goodsBuffersEntity.setRealStoreName(realStoreName);
                goodsBuffersEntity.setStoreName(zx);
                goodsBuffersEntity.setLastStoreStatus(goodsBuffersEntity.getStoreStatus());
                goodsBuffersEntity.setStoreStatus(2);
                goodsBuffersEntity.setStoreTime(new Date());
                if (!storeData.isEmpty()) {
                    AgvCallDataDto agvCallDataDto = storeData.get(i);
                    agvCallDataDto.setPos(goodsBuffersEntity.getName());
                    goodsBuffersEntity.setStoreData(JSONObject.toJSONString(agvCallDataDto));
                }
                goodsBuffersService.updateById(goodsBuffersEntity);
            }
        }
        return bestPlaceList;
    }

    /**
     * 搜索出当前组满足存放条件的空位
     *
     * @param allGoodsBuffers
     * @param groupId
     * @param num
     * @return
     */
    private List<GoodsBuffersEntity> searchBestPlaceListForPut(List<GoodsBuffersEntity> allGoodsBuffers, Integer groupId, Integer num) {
        List<GoodsBuffersEntity> bestPlaceList = new ArrayList<>();

        GoodsBuffersEntity lastExit = allGoodsBuffers.stream()
                .filter(item -> item.getStoreStatus().intValue() == 0)//有存放
                .filter(item -> item.getGroupId().intValue() == groupId.intValue())//当前组
                .sorted(Comparator.comparingInt(GoodsBuffersEntity::getId).reversed())//ID倒序
                .findFirst()
                .orElse(null);

        List<GoodsBuffersEntity> searchList = allGoodsBuffers.stream()
                .filter(item -> item.getStoreStatus().intValue() == 1)//无存放
                .filter(item -> item.getGroupId().intValue() == groupId.intValue())//当前组
                .filter(item -> item.getId() > (lastExit == null ? -1 : lastExit.getId()))//位置大于有存放
                .toList();
        if (searchList.size() >= num) {
            for (int i = 0; i < num; i++) {
                bestPlaceList.add(searchList.get(i));
            }
        }
        return bestPlaceList;
    }


    private List<GoodsBuffersEntity> findBestPlaceForTake(Integer num, String realStoreName) {
        List<GoodsBuffersEntity> bestPlaceList = new ArrayList<>();
        List<GoodsGroupEntity> allGoodsGroup = goodsGroupService.list();
        List<GoodsBuffersEntity> allGoodsBuffers = goodsBuffersService.list();
        // 从第1组-->第8组搜索，满足就拿，不满足则找最多的拿
        bestPlaceList = this.searchBestPlaceListForTake(allGoodsGroup, allGoodsBuffers, realStoreName, num);
        if (!bestPlaceList.isEmpty()) {
            for (int i = 0; i < bestPlaceList.size(); i++) {
                GoodsBuffersEntity goodsBuffersEntity = bestPlaceList.get(i);
                goodsBuffersEntity.setStoreStatus(3);
                goodsBuffersEntity.setStoreTime(new Date());
                goodsBuffersService.updateById(goodsBuffersEntity);
            }
        }
        return bestPlaceList;
    }

    private List<GoodsBuffersEntity> searchBestPlaceListForTake(List<GoodsGroupEntity> allGoodsGroup,
                                                                List<GoodsBuffersEntity> allGoodsBuffers,
                                                                String realStoreName, Integer num) {
        List<GoodsBuffersEntity> bestPlaceList = new ArrayList<>();
        Map<Integer, List<GoodsBuffersEntity>> searchListMap = new HashMap<>();
        for (GoodsGroupEntity group : allGoodsGroup) {
            GoodsBuffersEntity lastOtherExit = allGoodsBuffers.stream()
                    .filter(item -> item.getStoreStatus().intValue() == 0)//有存放
                    .filter(item -> item.getGroupId().intValue() == group.getId().intValue())//当前组
                    .filter(item -> !realStoreName.equals(item.getRealStoreName()))//非目标轴类型
                    .sorted(Comparator.comparingInt(GoodsBuffersEntity::getId).reversed())//ID倒序
                    .findFirst()
                    .orElse(null);

            List<GoodsBuffersEntity> searchList = allGoodsBuffers.stream()
                    .filter(item -> item.getStoreStatus().intValue() == 0)//有存放
                    .filter(item -> realStoreName.equals(item.getRealStoreName()))//目标轴类型
                    .filter(item -> item.getGroupId().intValue() == group.getId().intValue())//当前组
                    .filter(item -> item.getId() > (lastOtherExit == null ? -1 : lastOtherExit.getId()))//位置大于有存放
                    .toList();
            searchListMap.put(group.getId(), searchList);
            if (searchList.size() >= num) {
                bestPlaceList.addAll(searchList.subList(searchList.size() - num, searchList.size()));
                break;
            }
        }
        if (bestPlaceList.isEmpty()) {
            Map.Entry<Integer, List<GoodsBuffersEntity>> maxEntry = Collections.max(
                    searchListMap.entrySet(),
                    Map.Entry.comparingByValue(Comparator.comparingInt(List::size))
            );
            bestPlaceList = maxEntry.getValue();
        }
        return bestPlaceList;
    }

    public static void main(String[] args) {
        int num = 1;
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        System.out.println(list.subList(list.size() - num, list.size()));
    }
}
